package com.hernie.user.service;

import com.hernie.user.mail.MyJavaMail;
import com.hernie.user.mapper.UserMapper;
import com.hernie.user.pojo.User;
import com.hernie.user.vo.UserVO;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class RegisterService {

    @Resource
    private UserMapper userMapper;
    public Map<String, Object> register(User user)  {
        Map<String, Object> map = new HashMap<>();
        MyJavaMail myJavaMail = new MyJavaMail(user.getUsername(), user.getEmail());
        user.setUuid(myJavaMail.getUuid());
        user.setAction(0);
        if (userMapper.findByUsername(user.getUsername()) == null && userMapper.findByPhone(user.getPhone()) == null && userMapper.findByEmail(user.getEmail()) == null) {
            userMapper.insert(user);
            new Thread(myJavaMail).start();
            map.put("code", 200);
            map.put("msg", "注册成功，请验证邮箱！");
            map.put("data", user);
        }
        else{
            map.put("code", 500);
            map.put("msg", "注册失败！");
        }
        System.out.println("register----------end");
        return map;
    }
//    public Map<String, Object> checkEmail(String uuid, HttpSession session){
    public String checkEmail(String uuid, HttpSession session){
        Map<String, Object> map = new HashMap<>();
        User byUuid = userMapper.findByUuid(uuid);
        String s = null;
        if (byUuid != null){
            byUuid.setAction(1);
            byUuid.setUuid(null);
            byUuid.setLastlogintime(new Timestamp(System.currentTimeMillis()));
            userMapper.updateById(byUuid);
            session.setAttribute("user", byUuid);
            map.put("code", 200);
            map.put("msg", "验证成功！");
            map.put("data", byUuid);
            s = "redirect:index.html";
        }
        else{
            map.put("code", 500);
            map.put("msg", "请重新验证！");
            s = "redirect:demo.html";
        }
//        return map;
        return s;
    }
}
